<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="模板名称"></el-input>
      </el-form-item>
      <el-form-item label="主题" prop="subject">
        <el-input v-model="dataForm.subject" placeholder="主题"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <!-- 富文本编辑器, 容器 -->
        <div id="J_quillEditor"></div>
        <!-- 自定义上传图片功能 (使用element upload组件) -->
        <el-upload
          :action="uploadUrl"
          :show-file-list="false"
          :before-upload="uploadBeforeUploadHandle"
          :on-success="uploadSuccessHandle"
          style="display: none;">
          <el-button ref="uploadBtn" size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import Cookies from 'js-cookie'
  import 'quill/dist/quill.snow.css'
  import Quill from 'quill'
  export default {
    data () {
      var validateContent = (rule, value, callback) => {
        if (this.quillEditor.getLength() <= 1) {
          callback(new Error('必填项不能为空'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        quillEditor: null,
        quillEditorToolbarOptions: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block', 'image'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean']
        ],
        uploadUrl: '',
        dataForm: {
          id: 0,
          name: '',
          subject: '',
          content: ''
        },
        dataRule: {
          name: [
            { required: true, message: '必填项不能为空', trigger: 'blur' }
          ],
          subject: [
            { required: true, message: '必填项不能为空', trigger: 'blur' }
          ],
          content: [
            { validator: validateContent, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init () {
        this.visible = true
        this.$nextTick(() => {
          if (this.quillEditor) {
            this.quillEditor.deleteText(0, this.quillEditor.getLength())
          } else {
            this.quillEditorHandle()
          }
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.getTemplateInfo()
          }
        })
      },
      // 富文本编辑器
      quillEditorHandle () {
        this.quillEditor = new Quill('#J_quillEditor', {
          modules: {
            toolbar: this.quillEditorToolbarOptions
          },
          theme: 'snow'
        })
        // 自定义上传图片功能 (使用element upload组件)
        this.uploadUrl = `${window.SITE_CONFIG['baseURL']}/sys/oss/upload?token=${Cookies.get('token')}`
        this.quillEditor.getModule('toolbar').addHandler('image', () => {
          this.$refs.uploadBtn.$el.click()
        })
      },
      // 上传图片之前
      uploadBeforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
      },
      // 上传图片成功
      uploadSuccessHandle (response, file, fileList) {
        if (response && response.code === 0) {
          this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', response.data.src)
        } else {
          this.$message.error(response.msg)
        }
      },
      // 获取模版信息
      getTemplateInfo () {
        this.$http.get(`${window.SITE_CONFIG['baseURL']}/sys/mailtemplate/info/${this.dataForm.id}`).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm.name = data.template.name
            this.dataForm.subject = data.template.subject
            this.quillEditor.root.innerHTML = data.template.content
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http.post(
              `${window.SITE_CONFIG['baseURL']}/sys/mailtemplate/${!this.dataForm.id ? 'save' : 'update'}`,
              {
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'subject': this.dataForm.subject,
                'content': this.quillEditor.root.innerHTML
              },
              {
                headers: { 'content-type': 'application/x-www-form-urlencoded' }
              }
            ).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
